package com.longge;

public class CountSubarrays {

    public long countSubarrays(int[] nums, int k) {
        int max = 0;
        for (int num : nums) {
            max = Math.max(num, max);
        }

        int ans = 0;
        for (int i = k; i <= nums.length; i++) {
            ans += getSubCount(nums, i, max);
        }

        return ans;
    }

    private int getSubCount(int[] nums, int k, int max) {
        int count = 0, right = 0, left = 0, ans = 0;
        for (right = 0; right < nums.length; right++) {
            while (count < k&&right<nums.length) {
                if (max == nums[right]) {
                    count++;
                }
                right++;
            }

            while (count == k) {
                ans++;
                if (max == nums[left]) {
                    count--;
                }
                left++;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        long l = new CountSubarrays().countSubarrays(new int[]{1, 3, 2, 3, 3}, 2);
        System.out.println(l);
    }
}
